<template>
  <el-upload
    ref="uploadRef"
    list-type="picture-card"
    :limit="1"
    :show-file-list="false"
    :on-exceed="handleExceed"
    :http-request="(event) => handleRequest(event)"
    @update:file-list="handleUpdate"
  >
    <template #default>
      <div v-if="($attrs['file-list'] as any).length" class="pic-box">
        <img :src="($attrs['file-list'] as any)[0].url" alt="" />
      </div>
      <el-button v-else>选择</el-button>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadInstance, UploadRequestOptions } from 'element-plus'
import request from '@/utils/request'

defineOptions({
  name: 'UploadIdCard'
})

const emit = defineEmits(['update:file-list'])

const uploadRef = ref<UploadInstance | null>(null)

function handleExceed(files: File[]) {
  uploadRef.value?.clearFiles()
  uploadRef.value?.handleStart(files[0] as any)
}

// 自定义文件上传的请求
function handleRequest(options: UploadRequestOptions) {
  return request({
    url: '/admin/base/comm/upload',
    method: 'POST',
    // PS
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      // options.file 就是原始的文件信息对象
      file: options.file
    }
  })
}

function handleUpdate(event: any) {
  console.log('upload-id-card  handleUpdate', event)
  // 主动 emit 给父组件
  emit('update:file-list', event)
}
</script>

<style lang="scss" scoped>
.pic-box {
  width: 100%;
  height: 100%;
  overflow: hidden;

  img {
    width: 100%;
    display: block;
  }
}
</style>
